<?php
 
// no direct access
defined('_JEXEC') or die( 'Restricted access' );

jimport('joomla.application.component.model');

class SyncrModelSite extends JModel
{
	var $_id = null;
	var $_data = null;

	function __construct()
	{
		parent::__construct();

		$cid = JRequest::getVar('cid', array(0), '', 'array');
		$task = JRequest::getVar('task');
		
		$this->_id = (int)$cid[0];
		
		if ($task === 'edit') {
			$this->setId((int)$cid[0]);
		}
	}
	
	function setId($id)
	{	
		$this->_id		= $id;
		$this->_data	= null;
	}
	
	function &getData()
	{		
		if ($this->_loadData()) {
			$user = &JFactory::getUser();
		} else {
			$this->_initData();
		}
		
		return $this->_data;
	}

	function _loadData()
	{
		if (empty($this->_data))
		{
			$query = 'SELECT id'
				   .', name'
				   .', url'
				   .', color'
				   .', logo'
				   .', apikey'
				   .', image'
				   .', published'
				   .', checked_out'
				   .', checked_out_time'
				   .' FROM #__syncr_sites'
				   .' WHERE id = '.(int) $this->_id
				   ;				   
			$this->_db->setQuery($query);
			$this->_data = $this->_db->loadObject();
			
			return (boolean) $this->_data;
		}
		
		return true;
	}

	function _initData()
	{
		if (empty($this->_data))
		{
			$site = new stdClass();
			$site->id			= 0;
			$site->name			= null;
			$site->url			= null;
			$site->color		= null;
			$site->logo			= null;
			$site->apikey		= null;
			$site->image		= 0;
			$site->published	= 0;
			$site->checked_out	= 0;
			$site->checked_out_time	= 0;
			$this->_data		= $site;
			return (boolean) $this->_data;
		}
		return true;
	}
	
	function store($data)
	{
		$row =& $this->getTable();

		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		return $row->id;
	}
	
	function isCheckedOut( $uid=0 )
	{
		if ($this->_loadData())
		{
			if ($uid) {
				return ($this->_data->checked_out && $this->_data->checked_out != $uid);
			} else {
				return $this->_data->checked_out;
			}
		}
	}
	
	function checkout($uid = null)
	{
		if ($this->_id)
		{
			// Make sure we have a user id to checkout the article with
			if (is_null($uid)) {
				$user	=& JFactory::getUser();
				$uid	= $user->get('id');
			}
			// Lets get to it and checkout the thing...
			$weblink = & $this->getTable();
			if(!$weblink->checkout($uid, $this->_id)) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}

			return true;
		}
		return false;
	}
	
	function checkin()
	{
		if ($this->_id)
		{
			$weblink = & $this->getTable();
			if(! $weblink->checkin($this->_id)) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}
		return false;
	}
}